package com.wiz.weixin.manager;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

/**
 * 协议管理器
 * @author Hakeny
 */
@Service("httpManager")
@SuppressWarnings("all")
public class HttpManager {
	
	private final int poolThreads = 200;
	private PoolingHttpClientConnectionManager cm;
	private CloseableHttpClient cc;
	private RequestConfig requestConfig = RequestConfig.custom()
			.setSocketTimeout(25000).setConnectTimeout(25000)
			.setConnectionRequestTimeout(28000)
			.build();

	/**
	 * 获得工厂管理器，以此配置形式新建工厂
	 * @return
	 * @author Hakeny:degang.yang@downjoy.com
	 */
	private synchronized PoolingHttpClientConnectionManager getPHCManagerInstance() {
		if (cm == null) {
			cm = new PoolingHttpClientConnectionManager();
			// 连接池最大生成连接数200
			cm.setMaxTotal(poolThreads);
			// 设置默认(连接url)route最大连接数为200，即并发线程数,目前只直连了评论系统，故最大连接数与此值相同
			cm.setDefaultMaxPerRoute(poolThreads);
			// 实例：指定专门的route，设置最大连接数为50，可设置多个，但总数不可超过MaxTotal
			// HttpHost localhost=new HttpHost("192.168.0.198", 7041);
			// cm.setMaxPerRoute(new HttpRoute(localhost), 500);
		}
		return cm;
	}

	/**
	 * 获得http链接工厂
	 * @return
	 * @author Hakeny:degang.yang@downjoy.com
	 */
	private synchronized CloseableHttpClient getCloseableHttpClient() {
		if (cc == null) {
			cc = HttpClients.custom().setConnectionManager(getPHCManagerInstance()).build();
		}
		return cc;
	}

	/**
	 * 发起相应的http get请求
	 * @param httpClient
	 * @param uri
	 * @return
	 * @author Hakeny:degang.yang@downjoy.com
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private CloseableHttpResponse getHttpResponseByGet(CloseableHttpClient httpClient, URI uri)
			throws ClientProtocolException, IOException {
		HttpGet httpget = new HttpGet(uri);
		httpget.setConfig(requestConfig);
		CloseableHttpResponse response = null;
		response = httpClient.execute(httpget, HttpClientContext.create());
		return response;
	}
	
	/**
	 * 发起相应的http post请求
	 * @param httpClient
	 * @param host
	 * @param path
	 * @param formparams
	 * @return
	 * @throws URISyntaxException
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private CloseableHttpResponse getHttpResponseByPost(String url,List<NameValuePair> formparams,
			CloseableHttpClient httpClient) throws URISyntaxException,ClientProtocolException,IOException {
		HttpPost httpost = new HttpPost(url);
		  
	    UrlEncodedFormEntity urlEntity =  new UrlEncodedFormEntity(formparams, "UTF-8");  
	    httpost.setEntity(urlEntity);  
	    httpost.setConfig(requestConfig);
	  
	    return httpClient.execute(httpost);  
	}
	
	/**
	 * 获取response中的内容
	 * @param response
	 * @return
	 */
	private String getResponseContent(CloseableHttpResponse response) {
		String content = "";
		if (response != null) {
			HttpEntity httpEntity = response.getEntity();
			try {
				if (response.getStatusLine().getStatusCode() == 200) {
					if (httpEntity != null) {
						content = EntityUtils.toString(httpEntity);
					}
				} else {
					return content;
				}
			} catch (Exception e) {
				return content;
			} finally {
				try {
					if (httpEntity != null) {
						httpEntity.getContent().close();
					}
					response.close();
				} catch (IOException e) {
				}
			}
		}
		return content;
	}
	
	/**
	 * 获取http response
	 * @param url 连接地址
	 * @param formparams 参数
	 * @return
	 * @throws Exception
	 */
   public String getResponseByHttpPost(String url,
			List<NameValuePair> formparams) throws Exception{
	   return getResponseContent(getHttpResponseByPost(url,formparams,getCloseableHttpClient()));
   }
}
